package com.boot.web;

import com.alibaba.excel.EasyExcel;
import com.boot.entity.User;
import com.boot.entity.vo.UserVO;
import com.boot.listener.UserDataListener;
import com.boot.service.IUserService;
import com.boot.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Chunsheng.Zhang
 * @date 2021/1/11 11:02
 * @description : TODO
 */
@Slf4j
@RestController
@RequestMapping("/excel")
public class ExcelController {


    @Autowired
    private IUserService userService;



    /**
     * @description: excel导入数据库
     * @author: ChunSheng.Zhang
     * @date: 2021/1/11 11:06
     * @param userExcelFile
     * @return java.lang.String
     **/
    public String excelAnalysis(MultipartFile userExcelFile){
        try{
            //使用EasyExcel工具解析输入流
            EasyExcel.read(userExcelFile.getInputStream(),UserVO.class, new UserDataListener(userService)).sheet().headRowNumber(1).doRead();//从表格的第二行开始导入
        }catch (Exception e){
            e.printStackTrace();
            return "导入失败";
        }

        return "导入成功!";
    }




    /**
     * @description: 查询数据库并导出至excel表格
     * @author: ChunSheng.Zhang
     * @date: 2021/1/11 12:26
     * @param response
     * @param request
     * @return void
     **/
    @GetMapping("/selToExport")
    public void export2Web(HttpServletResponse response, HttpServletRequest request) {

        try {
            ExcelUtils.export2Web(response, "流入表", "流入信息", User.class, userService.selAllUser());
        } catch (Exception e) {
            log.error("报表导出异常:", e);
        }
    }






}
